<template>
  <div class="complete_self_list">
    <el-dialog
      title="完工登记"
      width="76%"
      top="10%"
      max
      :visible.sync="dialogTableVisible"
      v-dialogDrag
      :close-on-click-modal="false"
      customClass="mes_dialog">
      <div v-loading="saveState">
        <p class="form_title"><i class="iconfont icon-tishi"></i>报废数量为问题反馈中的报废数量</p>
        <div class="table_container">
          <el-table
            :data="tableList"
            ref="tableNode"
            :cell-class-name="setCellClass"
            border
            max-height="440">
            <mes-col-comp
              :key="index"
              v-for="(column, index) in columnList"
              :column="column"></mes-col-comp>
            <el-table-column
              align="center"
              width="100"
              prop="completeQuantity"
              fixed="right"
              :label="completeTitle">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.completeQuantity"
                  v-if="!scope.row.isShare"
                  size="mini"
                  placeholder="请输入"
                  :precision="0"
                  :controls="false"
                  :min="0"
                  :max="calcMaxNum(scope.row)"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              fixed="right"
              width="120"
              label="操作人员"
              prop="startWorkStaffName"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column
              align="center"
              fixed="right"
              width="100"
              label="消耗工时"
              prop="workingHours"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.workingHours"
                  size="mini"
                  placeholder="请输入"
                  :controls="false"
                  :precision="1"
                  :min="0"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              fixed="right"
              prop="remarks"
              min-width="200"
              label="备注"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.remarks"
                  size="mini"
                  placeholder="请输入备注"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              fixed="right"
              min-width="130"
              label="操作">
              <template slot-scope="scope">
              <span class="jump_item"
                    v-if="!scope.row.isShare"
                    :class="{is_disabled: !startWorkStaffList[scope.row.id] || startWorkStaffList[scope.row.id].length < 2}"
                    @click="showShare(scope)">工时分摊</span>
                <span class="jump_item"
                      @click="deleteItem(scope.$index)"
                      v-if="scope.row.isShare || turnoverWorkstageList.length > 1">删除</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <span slot="footer" class="dialog-footer mes_btn">
        <el-button type="primary" @click="submitData()">提交</el-button>
        <el-button @click="dialogTableVisible = false">取消</el-button>
      </span>
    </el-dialog>
    <share-select ref="ShareSelect" @saveShare="saveShare"></share-select>
  </div>
</template>

<script>
import completionCol from './completionCol'
import ShareSelect from './ShareSelect'

export default {
  name: 'CompleteRegister',
  components: {
    ShareSelect
  },
  data() {
    return {
      dialogTableVisible: false,
      saveState: false, // 保存状态
      columnList: completionCol, // 列配置
      completeTitle: '完工数量', // 完工数量label
      curScope: {}, // 当前操作行
      turnoverWorkstageList: [], // 工序信息缓存
      startWorkStaffList: {}, // 操作人员列表
      turnoverSerialCount: {}, // 工序刻字数量
      errMsg: '', // 完工提交错误提示
      tableList: [] // 表格填充数据
    }
  },
  methods: {
    /**
     * 打开弹窗
     * @param list 选中的工序列表
     */
    openDialog(list, type) {
      // 获取选中工序列表
      this.turnoverWorkstageList = list
      // 重置保存状态
      this.saveState = false
      // copy主工序列表
      this.tableList = JSON.parse(JSON.stringify(list))
      // 清空人员列表
      this.startWorkStaffList = {}
      // 判断操作者工作台还是检验工作台
      if (type === 'workShowInspection') {
        this.errMsg = '必填项不能为空'
        this.completeTitle = '合格数量'
      } else {
        this.errMsg = '必填项不能为空，刻字工序的完工数量和已生成序列号数量必须相同'
        this.completeTitle = '完工数量'
      }
      // 获取人员列表
      this.getStaffInfo()
      // 显示弹框
      this.dialogTableVisible = true
    },
    // 获取人员列表
    getStaffInfo() {
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/turnoverworkstage/turnoverWorkstage/getStaffInfo',
        data: {
          workstageIds: this.turnoverWorkstageList.reduce((pre, cur) => [...pre, cur.id], [])
        },
        noCommit: true
      }).then(res => {
        // 设置人员列表
        this.startWorkStaffList = res.data.staffs
        // 设置工序的刻字数量
        this.turnoverSerialCount = res.data.turnoverSerialCount
      })
    },
    // 显示分摊列表
    showShare(scope) {
      // 没有人员列表，或者没有分摊人员则不能进行分摊
      if (!this.startWorkStaffList[scope.row.id] || this.startWorkStaffList[scope.row.id].length < 2) return
      // 保存当前行数据
      this.curScope = scope
      // 打开分摊弹框
      this.$refs.ShareSelect.openDialog(this.startWorkStaffList[scope.row.id], scope.row.startWorkStaffId)
    },
    // 处理选择的分摊人员
    saveShare(list) {
      list.forEach((item, index) => {
        // if (this.tableList.some(tableItem => tableItem.id === this.curScope.row.id && tableItem.startWorkStaffId === item.id)) return
        // 添加人员分摊项
        this.addItem({
          id: this.curScope.row.id,
          index: this.curScope.$index + index + 1,
          startWorkStaffId: item.id,
          startWorkStaffName: item.name
        })
      })
    },
    // 添加分摊项
    addItem({id, index, startWorkStaffId, startWorkStaffName}) {
      // 设置添加的分摊人已选
      this.startWorkStaffList[id].find(item => item.id === startWorkStaffId).disabled = true
      let obj = {
        isShare: true,
        id: id,
        startWorkStaffId: startWorkStaffId,
        startWorkStaffName: startWorkStaffName,
      }
      this.tableList.splice(index, 0, obj)
    },
    // 删除列表项
    deleteItem(index) {
      let row = this.tableList[index]
      if (row.isShare) {
        // 清除删除的分摊人
        this.startWorkStaffList[row.id].find(item => item.id === row.startWorkStaffId).disabled = false
        this.tableList.splice(index, 1)
      } else {
        this.turnoverWorkstageList = this.turnoverWorkstageList.filter(item => item.id !== row.id)
        this.tableList = this.tableList.filter(item => item.id !== row.id)
      }
    },
    // 设置单元格样式
    setCellClass({row, column}) {
      switch (column.property) {
        case 'completeQuantity':
          if (!row.isShare && isNaN(row.completeQuantity)) {
            return 'cell_isAfter'
          } else if (!row.isShare && row.workstageName.includes('刻字') && row.completeQuantity !== this.turnoverSerialCount[row.id]) {
            return 'cell_isAfter'
          }
          break
        case 'workingHours':
          if (isNaN(row.workingHours)) return 'cell_isAfter'
          break
        case 'remarks':
          if (row.completeQuantity !== undefined && row.completeQuantity < this.calcMaxNum(row) && !row.remarks) return 'cell_isAfter'
          break
      }
    },
    // 列表项检查
    saveItem(row) {
      if (!row.isShare && (isNaN(row.completeQuantity))) {
        return false
      } else if (!row.isShare && row.workstageName.includes('刻字') && row.completeQuantity !== this.turnoverSerialCount[row.id]) {
        return false
      } else if (!row.startWorkStaffId) {
        return false
      } else if (isNaN(row.workingHours)) {
        return false
      } else if (row.completeQuantity !== undefined && row.completeQuantity < this.calcMaxNum(row) && !row.remarks) {
        return false
      }
      return true
    },
    /**
     * 提交数据
     */
    submitData() {
      if (this.saveState) return
      this.saveState = true
      if (this.tableList.some(item => !this.saveItem(item))) return this.tipMessage('error', this.errMsg)
      let workstageList = this.tableList.filter(item => item.hasOwnProperty('completeQuantity'))
      let hoursList = []
      this.tableList.map(item => {
        hoursList.push({
          workstageId: item.id,
          staffId: item.startWorkStaffId,
          workingHours: item.workingHours,
          remarks: item.remarks
        })
      })
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/turnoverworkstage/turnoverWorkstage/completeWorkReg',
        data: {
          turnoverWorkstageList: workstageList,
          workingHoursList: hoursList
        },
        noCommit: true
      }).then(() => {
        this.tipMessage('success', '完工登记成功')
        this.dialogTableVisible = false
        this.$emit('submitSuccess')
      }).catch(() => {
        this.saveState = false
      })
    },
    // 判断最大完工数量
    calcMaxNum(row) {
      let startData = row.inputQuantity || row.productionQuantity
      return startData - row.scrapQuantity
    },
    /**
     * 提示
     * @param str 提示内容
     */
    tipMessage(type, str) {
      this.$message({
        type: type,
        message: str,
        duration: 1500,
        center: true
      })
    }
  }
}
</script>

<style scoped lang="less">
  .complete_self_list{
    .el-input-number{
      width: 100%;
    }
  }
</style>
<style lang="less">
  .complete_self_list{
    .cell_isAfter .el-input__inner{
      border-color: #f8000f !important;
    }
  }
</style>
